package etc

import (
	"encoding/json"
	"flag"
	"io/ioutil"
	"path"
	"strings"
	"path/filepath"
)

var Param *arg

type arg struct {
	Json string
	Dir  string
	File string
	Path string
	Zip  string
	Cove bool
	Rem  bool
}

// 命令参数初始化
func init() {
	if Param != nil {
		return
	}

	Arg := &arg{}

	j := flag.String("json", "", ".json配置文件地址")
	d := flag.String("d", "", "上传指定目录")
	f := flag.String("f", "", "上传指定文件")
	p := flag.String("p", "", "七牛云存储目录名称")
	z := flag.String("z", "", "压缩目录或文件,指定压缩名称")
	c := flag.Bool("c", true, "是否刷新七牛云存储CDN")
	r := flag.Bool("r", true, "是否删除压缩文件")

	flag.Parse()

	Arg.Json = *j
	Arg.Dir = *d
	Arg.File = *f
	Arg.Path = *p
	Arg.Zip = *z
	Arg.Cove = *c
	Arg.Rem = *r

	if len(Arg.Dir) > 0 {
		Arg.Dir, _ = filepath.Abs(Arg.Dir)
	} else {
		Arg.Dir = ROOT() + PATH()
	}

	if len(Arg.File) > 0 {
		Arg.File, _ = filepath.Abs(Arg.File)
	}

	if len(Arg.Zip) > 0 {
		Arg.Zip = path.Base(Arg.Zip)
		if len(path.Ext(Arg.Zip)) <= 0 {
			Arg.Zip = Arg.Zip + ".zip"
		}
	}

	if len(Arg.Json) > 0 {
		initETC(Arg.Json)
	}

	Param  = Arg
	Domain = strings.TrimRight(Domain, "/") + "/"
}

// 设置变量初始化
func initETC(fileName string) {
	if !IS(fileName) {
		panic(fileName + " is not exists.")
	}

	type V struct {
		Bucket      string   `json:"bucket"`
		Domain      string   `json:"domain"`
		AccessKey   string   `json:"accessKey"`
		SecretKey   string   `json:"secretKey"`
		FileExt     []string `json:"fileExt"`
		ZipPassword string   `json:"zipPassword"`
	}

	data, err := ioutil.ReadFile(fileName)
	if err != nil {
		panic(err)
	}

	v := &V{}
	if err := json.Unmarshal([]byte(data), v); err != nil {
		panic(err)
	}

	if len(v.Domain) > 0 {
		Domain = v.Domain
	}

	if len(v.Bucket) > 0 {
		Bucket = v.Bucket
	}

	if len(v.AccessKey) > 0 {
		AccessKey = v.AccessKey
	}

	if len(v.SecretKey) > 0 {
		SecretKey = v.SecretKey
	}

	if len(v.ZipPassword) > 0 {
		ZipPassword = v.ZipPassword
	}

	if len(v.FileExt) > 0 {
		FileExt = v.FileExt
	}
}
